package com.daniel.thingofday;

import java.io.*;
import java.util.Calendar;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class GetThingOfDayActivity extends Activity {
	String date;
	TextView debugText;
	WebView showThePage;
	Button datePicker;
	/*
	--If App Has Submit Page--
	Button toSubmitPage;
	*/
	Button alertHelp;
	Button toList;
	static final int DATE_DIALOG_ID = 0;
    /** Called when the activity is first created. */
	String dateAdded;
	String desc;
	String url = "http://www.google.com/";
	String site;
	private int mYear;
	private int mMonth;
	private int mDay;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        AlertDialog.Builder startDialog = new AlertDialog.Builder(this);
        startDialog.setMessage("This app, once you choose a date, will fetch the set 'thing of the day' for that date.  To view a list of all the things for this month, click the recent button.  Look down for a tutorial!");
        startDialog.setNeutralButton("Start Using!", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
        startDialog.show();
        Calendar c = Calendar.getInstance();
        showThePage = (WebView) findViewById(R.id.web_engine);
        showThePage.setWebViewClient(new WebC());
        showThePage.loadUrl("http://www.youtube.com/watch?v=i2vNWGynF2U");
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        debugText = (TextView) findViewById(R.id.debugText);
        //String dataToShow = connect("http://mcauthserv.net76.net/TOD.json", 7, 26, 2012);
        //debugText.setText(dataToShow);
        debugText.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Intent.ACTION_WEB_SEARCH, Uri.parse(url));
				startActivity(intent);
			}
		});
        datePicker = (Button) findViewById(R.id.pickADate);
        alertHelp = (Button) findViewById(R.id.alertHelp);
        toList = (Button) findViewById(R.id.toList);
        toList.setOnClickListener(new OnClickListener() {
		
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent toList = new Intent(GetThingOfDayActivity.this, listOfRecent.class);
				toList.putExtra("year", mYear);
				toList.putExtra("month", mMonth);
				startActivity(toList);
				finish();
			}
		});
        alertHelp.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder alert = new AlertDialog.Builder(GetThingOfDayActivity.this);
				alert.setTitle("Help Alert");
				alert.setMessage("Enter a date to view the thing for that day, and go to the submit page to submit your own!");
				alert.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
				alert.show();
			}
		});
        datePicker.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        /* 
        --If App Has Submit Page--
        toSubmitPage = (Button) findViewById(R.id.toSubmitPage);
        toSubmitPage.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent toSubmit = new Intent(GetThingOfDayActivity.this, subPage.class);
				startActivity(toSubmit);
			}
		});
		*/
    }
    
    public String connect(String url, int month, int day, int year)
    {
        if(isNetworkAvailable())
        {
        // Create the httpclient
        HttpClient httpclient = new DefaultHttpClient();
       
        // Prepare a request object
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Cache-Control", "no-cache");
        // Declare a response
        HttpResponse response;
     
        // Declare a return string
        String returnString = null;
        try {
        	 
            // Open the webpage.
            response = httpclient.execute(httpget);
 
            if(response.getStatusLine().getStatusCode() == 200){
                // Connection was established. Get the content. 
 
                HttpEntity entity = response.getEntity();
                // If the response does not enclose an entity, there is no need
                // to worry about connection release

                if (entity != null) {
                        // A Simple JSON Response Read
                        InputStream instream = entity.getContent();
                        // Load the requested page converted to a string into a JSONObject.
                        JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
                        //String query = jsonResponse.getString("query");
                        //JSONArray suggestions = jsonResponse.getJSONArray("7/27/2012");
                        //my code
	                        JSONObject data = jsonResponse.getJSONObject(month+"/"+day+"/"+year);
	                        FileOutputStream fos = openFileOutput("ThingOfDayCache", Context.MODE_PRIVATE);
	                        fos.write(jsonResponse.toString().getBytes());
	                        fos.close();
	                        //JSONObject data = jsonResponse.getJSONObject("7/27/2012");
	                        returnString = "The thing for that day is: ";
	                    	for (int i = 0; i < data.length(); i++) {
	                    		returnString += "\n\t" + data.getString(""+i);
	                    		if(URLUtil.isValidUrl(data.getString(""+i)))
	                    		{
	                    			url = data.getString(""+i);
	                    			showThePage.loadUrl(url);
	                    		}
	                    	}
                   // Close the stream.
                   instream.close();
                }
            else {
                // code here for a response othet than 200.  A response 200 means the webpage was ok
                // Other codes include 404 - not found, 301 - redirect etc...
                // Display the response line.
                returnString = "Unable to load page - " + response.getStatusLine();
            }
        }
        }
        
        catch (IOException  ex) {
            // thrown by line 80 - getContent();
            // Connection was not established
            returnString = "Connection failed; " + ex.getMessage();
        }
        catch (JSONException ex){
            // JSON errors
            returnString = "Error!  Please make sure that there is a value for that date, and that you have a network connection (or that it is in your cache)!";
        }
        return returnString;
        }
        else
        {
        	String returnString = "";
        	FileInputStream instream;
			try {
				instream = openFileInput("ThingOfDayCache");
	        	JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
	        	JSONObject data = jsonResponse.getJSONObject(month+"/"+day+"/"+year);
	            returnString = "The thing for that day is: ";
	        	for (int i = 0; i < data.length(); i++) {
	        		returnString += "\n\t" + data.getString(""+i);
            		if(URLUtil.isValidUrl(data.getString(""+i)))
            		{
            			url = data.getString(""+i);
            			showThePage.loadUrl(url);
            		}
			}} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return returnString;
        }
    }
    

    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    DatePickerDialog.OnDateSetListener mDateSetListener =
    	    new DatePickerDialog.OnDateSetListener() {
    	        public void onDateSet(DatePicker view, int year, 
    	                              int monthOfYear, int dayOfMonth) {
    	            String data = connect("http://mcauthserv.net76.net/TOD.json", monthOfYear + 1, dayOfMonth, year);
    	            debugText.setText(data);
    	        }};
    @Override
    protected Dialog onCreateDialog(int id) {
       switch (id) {
       case DATE_DIALOG_ID:
          return new DatePickerDialog(this,
                    mDateSetListener,
                    mYear, mMonth, mDay);
       }
       return null;
    }
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
     
}
    